package cn.ihna.demo.client.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @author xianyingda@gmail.com
 * @serial
 * @since 2020-08-15 01:07
 */
@Component
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    /**
     * 当前客户端读取到数据之后就会执行这个handler
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        String message = msg.toString(StandardCharsets.UTF_8);
        System.out.println("client read message:" + message);
    }

    /**
     * 连接建立以后
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("I am 10", StandardCharsets.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
